package demo.server.run;

import java.io.File;

import org.apache.log4j.xml.DOMConfigurator;
import org.jconfig.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import core.util.StringUtil;
import demo.server.common.ServerConstant;
import demo.server.log.WriteLog;
import demo.server.model.QueueModel;
import demo.server.socket.DemoServer;

public class ServerRun {
	
	private static QueueModel que = new QueueModel();
	private int port;
	public Logger logI = LoggerFactory.getLogger("LogInfo");
	public void loadConfig(){
		ServerConfig serverConfig = new ServerConfig();
		serverConfig.loadConfig();
		Configuration config = ServerConfig.getConfig();
		String portString = config.getProperty("PORT", "1234", "SOCKET");
		if (StringUtil.isCastToInteger(portString)) {
			port = new Integer(portString);
		} else {
			port = 0;
		}
	}
	
	public void test(){
		
	}
	
	public void loadLogConfig(){
		String path = ServerConstant.logParth + "socketLib" + File.separator;
		DOMConfigurator.configureAndWatch(path + "serverConfig.log4j.xml");
	}
	
	private int getPort(){
		return port;
	}
	
	public static void main(String[] args) {
		final ServerRun serverRun = new ServerRun();
		serverRun.loadConfig();
		serverRun.loadLogConfig();
		DemoServer demoServer = new DemoServer(serverRun.getPort(), ServerRun.que);
		demoServer.run();
		WriteLog writeLog = new WriteLog(ServerRun.que);
		writeLog.start();
		
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                	serverRun.logI.info("system kill");
                } catch (Throwable ex) {
                }
            }
        }, "HOOK    "));
	}
	
}
